package com.sky.common.node.sort;

import com.sky.business.sys.domain.Node;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 最低负载选择器
 *
 */
public class SystemLoadNodeSorter implements NodeSorter {


    @Override
    public List<Node> sort(List<Node> nodeList, boolean gpuSupport) {
        double maxCpuIdle = 0;
        double maxMemory = 0;
        double maxGpuMemory = 0;
        for (Node node : nodeList) {
            double cpuIdle = node.getCpuPhysicalCore() * node.getCpuIdlePercent() / 100.0;
            if (cpuIdle > maxCpuIdle) {
                maxCpuIdle = cpuIdle;
            }
            if (node.getFreeMemory() > maxMemory) {
                maxMemory = node.getFreeMemory();
            }
            if (node.getGpuIdleMemory() > maxGpuMemory) {
                maxGpuMemory = node.getGpuIdleMemory();
            }
        }
        List<NodeScore> nodeScoreList = new ArrayList<>();
        for (Node currNode : nodeList) {
            double cpuIdle = currNode.getCpuPhysicalCore() * currNode.getCpuIdlePercent() / 100.0;
            double cpuScore = cpuIdle / maxCpuIdle;
            double memoryScore = currNode.getFreeMemory() / maxMemory;
            double gpuScore;
            if (gpuSupport) {
                gpuScore = currNode.getGpuIdleMemory() / maxGpuMemory;
            } else {
                gpuScore = 1 - currNode.getGpuIdleMemory() / maxGpuMemory;
            }
            double currNodeScore = cpuScore + memoryScore + gpuScore;
            nodeScoreList.add(new NodeScore(currNode,currNodeScore));
        }
        Collections.sort(nodeScoreList);
        return nodeScoreList.stream().map(NodeScore::getNode).collect(Collectors.toList());
    }
}
